/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;

import org.apache.http.Header;

import logic.bean.BookInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.Util;
import logic.util.logutil.LogUtil;


/**
 * @Project： Shwread
 * @Title：CommonWebActivity
 * @Description：
 * @Author：wayne
 * @Date：2015年3月9日上午11:29:55
 */
public class CommonWebActivity extends BaseBusinessActivity implements OnClickListener {

    private WebView webView = null;
    private WebChromeClient chromeClient = null;
    private View myView = null; //全频时View显示
    private TextView tvTitle = null;
    private Button btnBack = null;
    private FrameLayout fLayWebView = null;
    private View rlayTitle = null;
    private CustomViewCallback myCallBack = null;
    private LoadingView loadingView = null;

    private UserDao userDao;
    private UserBean user;

    private String mTitle = "";
    private String mUrl = "";
    private String targetType = "";
    private String targetValue = "";

    /**
     * 应用是否退出
     */
    private boolean isAppExit = false;

    private int mark = 0;
    private Context context;

    @Override
    public Handler getUIHandler() {
        return myHandler;
    }

    @Override
    protected void onPause() {
        super.onPause();
//        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.resumeTimers();
    }

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case 1:
                    String bookId = bundle.getString("bookId");
                    String name = bundle.getString("bookName");
                    String type = bundle.getString("bookType");
                    gotoBookDetail(bookId, name, type);
                    break;

                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.webview_lay);
        final Bundle bundle = getIntent().getExtras();
        mTitle = bundle.getString(DefaultConsts.title_s);
        mUrl = bundle.getString(DefaultConsts.req_url_s);
        mark = bundle.getInt("mark");
        context = this;

        if (bundle.containsKey(DefaultConsts.COMMENT_TARGET_TYPE) && bundle.containsKey(DefaultConsts.COMMENT_TARGET_VALUE)) {
            targetType = bundle.getString(DefaultConsts.COMMENT_TARGET_TYPE);
            targetValue = bundle.getString(DefaultConsts.COMMENT_TARGET_VALUE);
        }

        if (getIntent().hasExtra(DefaultConsts.message_send_id)) {
            if (Util.isEmpty(Const.phone_number)) {
                isAppExit = true;
                UserBean user = UserDao.getInstance(this).getLastLoginUser();
                Const.phone_number = user.getAccount();
                Const.login_key = user.getKey();
            }
            final int msgViewId = getIntent().getIntExtra(DefaultConsts.message_send_id, -1);
            //			new ReadMsgBySendIdAction(this, String.valueOf(msgViewId), new MyAction()).start();
            NewActionHelp.readMsgBySendId(this, String.valueOf(msgViewId), new MyHandler());
        }

        initView();
        initLoadingView();
        setListener();
        setWebView();

        if (savedInstanceState != null) {
            webView.restoreState(savedInstanceState);
        }

    }

    @Override
    protected void onDestroy() {
        finish();
        super.onDestroy();
    }

    void initView() {
        fLayWebView = (FrameLayout) findViewById(R.id.webview_flay);
        webView = (WebView) findViewById(R.id.webview_web);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(mTitle);
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        rlayTitle = findViewById(R.id.common_title_layout);
        loadingView = (LoadingView) findViewById(R.id.webview_loading_view);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        //		loadingView.setLoadingAnim(R.anim.column_switch_anim);
        loadingView.changeLoadingStatus(0);

        loadingView.setVisibility(View.VISIBLE);
        /** 用GONE会导致部分视频加载不出来 */
        fLayWebView.setVisibility(View.INVISIBLE);
    }

    void setListener() {
        btnBack.setOnClickListener(this);
    }

    @SuppressLint("SetJavaScriptEnabled")
    void setWebView() {
        WebSettings webSeting = webView.getSettings();
        webSeting.setJavaScriptEnabled(true);
        webSeting.setJavaScriptCanOpenWindowsAutomatically(true);

        webView.setWebViewClient(new MyWebviewCient());

        chromeClient = new MyChromeClient();

        webView.setWebChromeClient(chromeClient);
        webSeting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSeting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(true);
        webSeting.setSupportZoom(false);
        webSeting.setPluginState(WebSettings.PluginState.ON);
        webSeting.setLoadWithOverviewMode(true);
        webSeting.setUseWideViewPort(true); //适应屏幕

        if (Util.isEmpty(mUrl)) {
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        } else {
            webView.loadUrl(Util.addUrlTimestamp(mUrl));
        }

        addJavaScriptMap(new SubMaintenanceJavaScriptInterface(), "qyreader");
    }

    @Override
    public void onBackPressed() {
        if (myView == null) {
            webView.onPause(); //退出播放停止
            if (webView.canGoBack() && !"5".equals(targetType)) webView.goBack();
            else {
                if (!existMainActivity()) {
                    startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
                }
                setResult(RESULT_OK);
                super.onBackPressed();
            }

        } else {
            chromeClient.onHideCustomView();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        webView.saveState(outState);
    }

    public void addJavaScriptMap(Object obj, String objName) {
        webView.addJavascriptInterface(obj, objName);
    }

    public class MyWebviewCient
            extends
            WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            WebResourceResponse response = null;
            response = super.shouldInterceptRequest(view, url);
            return response;
        }

        /*
         * 点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
         * 因此，要在shouldOverrideUrlLoading方法中
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //使用当前的WebView加载页面
            if (url.contains("tel:")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        /*
         * 网页加载完毕(仅指主页，不包括图片)
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        /*
         * 网页加载完毕(仅指主页，不包括图片)
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

        /*
         * 加载页面资源
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        /*
         * 错误提示
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            LogUtil.e("webview", description);
            super.onReceivedError(view, errorCode, description, failingUrl);
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

    }

    public class MyChromeClient
            extends
            WebChromeClient {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (myView != null) {
                callback.onCustomViewHidden();
                return;
            }
            fLayWebView.removeView(webView);
            fLayWebView.addView(view);
            rlayTitle.setVisibility(View.GONE);
            myView = view;
            myCallBack = callback;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }

        @Override
        public void onHideCustomView() {
            if (myView == null) {
                return;
            }
            fLayWebView.removeView(myView);
            myView = null;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            fLayWebView.addView(webView);
            rlayTitle.setVisibility(View.VISIBLE);
            myCallBack.onCustomViewHidden();
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        /*
         * 此处覆盖的是javascript中的alert方法。
         * 当网页需要弹出alert窗口时，会执行onJsAlert中的方法
         * 网页自身的alert方法不会被调用。
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            /*
			 * 此处代码非常重要，若没有，android就不能与js继续进行交互了，
			 * 且第一次交互后，webview不再展示出来。
			 * result：A JsResult to confirm that the user hit enter.
			 * 我的理解是，confirm代表着此次交互执行完毕。只有执行完毕了，才可以进行下一次交互。
			 */
            result.confirm();
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return true;
        }

        /*
         * 如果页面被强制关闭,弹窗提示：是否确定离开？
         * 点击确定 保存数据离开，点击取消，停留在当前页面
         */
        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                if (mark == 1) {
                    onBackAd();
                } else if (mark == 2) {
                    onDestroy();
                } else {
                    onBackPressed();
                }
                break;
            default:
                break;
        }

    }

    private void onBackAd() {
        userDao = UserDao.getInstance(context);
        user = userDao.getLastLoginUser();
        if (null != user && user.getIsKeepPwd() == 1) {
            onDestroy();
        } else {
            goLoginActivity();
        }
    }

    void goLoginActivity() {
        Intent intent = new Intent();
        intent.setClass(this, NewLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        this.finish();
    }

    private class MyHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (isAppExit) Const.clear();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            if (isAppExit) Const.clear();
        }

    }

    private class MyAction
            extends
            BaseAction {
        @Override
        public void OK(Object obj) {
            if (isAppExit) Const.clear();
        }

        @Override
        protected void onError() {
            super.onError();
            if (isAppExit) Const.clear();
        }
    }

    private void sendToastMessage(String bookId, String bookName, String bookType) {

        Message msg = Message.obtain();
        msg.what = 1;
        Bundle bundle = new Bundle();
        bundle.putString("bookId", bookId);
        bundle.putString("bookName", bookName);
        bundle.putString("bookType", bookType);
        msg.setData(bundle);
        myHandler.sendMessage(msg);
    }

    private void gotoBookDetail(String bookId, String name, String bookType) {
        BookInfo info = new BookInfo();
        info.setBookId(Long.parseLong(bookId));
        info.setName(name);
        info.setContent_type(bookType);
        //#ifdef SHOW_OLDBOOKDETAIL
        //$ Intent intent = new Intent(this, BookDetailActivity.class);
        //#else
        Intent intent = new Intent(this, NewBookDetailActivity.class);
        //#endif
        intent.putExtra("BookInfo", info);
        startActivity(intent);

    }

    final class SubMaintenanceJavaScriptInterface {

        /**
         * 在屏幕下端提示用户
         */
        public void setBookInfo(String bookId, String bookName, String bookType) {
            LogUtil.d("--", "bookId：" + bookId + " | bookName:" + bookName + " |bookType:" + bookType);
            sendToastMessage(bookId, bookName, bookType);
        }

        /**
         * 提供给B端打印日志
         */
        public void fireLog(String log) {
            LogUtil.d("dddd", log);
        }

        /**
         * 假如有历史记录 回退历史记录 否则退出容器
         */
        public void goBack() {
            BaseBusinessActivity.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    onBackPressed();
                }
            });
        }
    }

}
